package data;

import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;

public class BigDecimalDemo {
    public static void main(String[] args) {
        setBigDecimal("66.666888",6);
        Date t1 = new Date();
        Date t2 = new Date();
        compareTimeDate(t1,t2);
       
    }

    /**
     * 设置BigDecimal类型数据的小数位数
     *
     * @param num   源数据
     * @param digit 保留的小数位数
     */
    public static void setBigDecimal(String num, int digit) {
        BigDecimal data = new BigDecimal(num);
        //设置BigDecimal类型数据的小数位数为5为小数
        BigDecimal data1 = data.setScale(digit, BigDecimal.ROUND_HALF_UP);
        System.out.println("data1:"+data1+",data:"+data);
        //计算两个BigDecimal类型数据的差值
        BigDecimal d=data1.subtract(data);
        //比较两个BigDecimal类型数据的大小
        int diff=data1.compareTo(data);
        System.out.println("diff:"+diff+",d:"+d);
    }

    /**
     * 计算两个时间相差的天数
     * @param start 开始日期
     * @param end 结束日期
     * @return 相差的天数
     */
    public static int compareTimeDate(Date start, Date end) {
        Calendar cal1 = Calendar.getInstance();
        cal1.setTime(start);

        Calendar cal2 = Calendar.getInstance();
        cal2.setTime(end);
        int day1 = cal1.get(Calendar.DAY_OF_YEAR);
        int day2 = cal2.get(Calendar.DAY_OF_YEAR);

        int year1 = cal1.get(Calendar.YEAR);
        int year2 = cal2.get(Calendar.YEAR);
        if (year1 != year2)   //不同一年
        {
            int timeDistance = 0;
            for (int i = year1; i < year2; i++) {
                if (i % 4 == 0 && i % 100 != 0 || i % 400 == 0)    //闰年
                {
                    timeDistance += 366;
                } else    //不是闰年
                {
                    timeDistance += 365;
                }
            }

            return timeDistance + (day2 - day1);
        } else    //同一年
        {
            System.out.println("判断day2 - day1 : " + (day2 - day1));
            return day2 - day1;
        }
    }

}
